import { defineStore } from 'pinia'
import { asyncRoutes, constantRoutes } from '@/router'
import { useUserStore } from '@/store/user'

function hasPermission(userRoles, route) {
  if (!route.meta || !route.meta.roles) return true
  return userRoles.some((role) => route.meta.roles.includes(role))
}

function filterAsyncRoutes(routes, userRoles) {
  const res = []
  routes.forEach((route) => {
    const tmp = { ...route }
    if (hasPermission(userRoles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, userRoles)
      }
      res.push(tmp)
    }
  })
  return res
}

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    addRoutes: []
  }),
  actions: {
    generateRoutes() {
      const userStore = useUserStore()
      return new Promise((resolve) => {
        const userRoles = userStore.userInfo?.roles || []
        const accessedRoutes = filterAsyncRoutes(asyncRoutes, userRoles)
        this.addRoutes = accessedRoutes
        this.routes = constantRoutes.concat(accessedRoutes)
        resolve(accessedRoutes)
      })
    }
  }
})
